在android 使用 Network 需要宣告權限
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
使用OkHttp與Retrofit第三方套件做網路連線為例:
OkHttp: HTTP 連線的第三方套件的操作。
Retrofit:通常與 OkHttp 並用,將API 定義與將資料轉成物件來操作,其規範的REST API 框架讓程式好寫易維護。
import libary
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.14.9"
}
*使用OkHttp 建立 UserApi api *
class ApiClient {
private val okHttp: Call.Factory
private val retrofit: Retrofit
private val testApi: TestApi
constructor(baseUrl: String = "api path") {
this.okHttp = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply { setLevel(HttpLoggingInterceptor.Level.NONE); })
.build()
this.retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(this.okHttp)
.addConverterFactory(GsonConverterFactory.create())
.build()
this.testApi = retrofit.create(TestApi::class.java)
}
suspend fun getTest(Id: Int): Test {
try {
val response = userApi.getUser(userId)
return if (response.isSuccessful) {
response.body()!!.data
} else {
throw Exception("should success")
}
} catch (e: Exception) {
throw e
}
}
}
UserApi getTest func
interface TestApi {
companion object {
const val PATH_ID = "id"
}
@GET("users/{$PATH_ID}")
suspend fun getTest(@Path(PATH_ID) Id: Int): Response<ParsingData<Test>>
}
data class ParsingData<T>(
@SerializedName("data") val id: data
)
使用Gson UserApi GSON 轉為物件
class Test(
@SerializedName("id") val id: Int,
@SerializedName("name") var name: String
)
提醒一下,要注意 OkHttp與 Retrofit 版本支援 , Android 4.x(含以下)的版本,OkHttp 只能用 3.12.x,Retrofit 只能用 2.6.4。
reference:https://square.github.io/retrofit/
reference:https://developer.android.com/training/basics/network-ops/connecting
reference:https://www.notion.so/Network-10-7-Cateyes-0c18aaf956ba4c7487e6116f29730263
reference:https://ithelp.ithome.com.tw/articles/10188660